import userAgreementPopup from '@/components/user-agreement-popup/user-agreement-popup.vue' //免责

export default {
  components: {
    userAgreementPopup, //弹出框组件
  },
  data() {
    return {
      showClearIcon: false, //input后面的小叉叉
      placeholder: '请输入手机号', //input默认提示
      showPopup: false, //弹窗
      showtitle: false, //小标题的显示隐藏
      UserName: '', //input输入的值
      isAgree: true, //勾选免责
      oldUser: '', //老用户
      historyInfo: [],
      isFocus: false,
      quickUser: '',
      phone: '', //手机号
      isRegister: false, //是否已经注册
      phoneLength: '',//号码位数
      maxphone: 13
    }
  },
  computed: {
    isDisabled() {
      if (this.phone.length === 11) {
        return false
      }
      return true
    },
    btnText() {
      if (this.quickUser && this.UserName === this.quickUser) {
        return '下一步'
      }
      return '获取验证码'
    },
    phoneList() {
      const len = this.UserName.length
      if (len) {
        return this.historyInfo.filter(item => {
          return item.slice(0, len) === this.UserName
        })
      }
      return this.historyInfo
    },
  },

  watch: {
    phone(val) {
      // console.log(val.length)
      if (val.length === 11) {
        this.checkIsRegister()
        this.phoneLength=false
      }else{
        this.phoneLength=true
      }
    },
  },
  onLoad(e) {
    const _this = this

    // #ifdef APP-PLUS
    //获取历史登录记录
    plus.device.getInfo({
      success: function (res) {
        const imei = res.imei.length < 2 ? res.uuid : res.imei
        _this.$store.commit('user/setImei', imei)
        _this.verifyMobile(imei)
      },
      complete: function (err) {},
    })
    // #endif

    if (e.number) {
      this.phone = e.number
      this.UserName =
        this.phone.slice(0, 3) +
        ' ' +
        this.phone.slice(3, 7) +
        ' ' +
        this.phone.slice(7)
      this.showClearIcon = true
      this.showSmalltitle()
    }
  },
  //监听默认返回事件
  onBackPress(e) {
    return true
  },
  methods: {
    //input后面的小叉叉
    clearIcon() {
      this.UserName = ''
      this.phone = ''
      this.showClearIcon = false //隐藏小叉叉
      this.showtitle = false //隐藏小标题
      // this.isAgree = true //不勾选免责
      this.placeholder = '请输入手机号'
      this.isFocus = false
    },
		    //实时监控--手机号--input输入的值
    onInput(event) {
      this.phone = event.detail.value
      this.$u.debounce(this.clearInput, 100)
    },
    //实时监控input输入的值
    clearInput() {
      const data = this.phone.replace(/[^\d.]/g, '')
      this.phone = data.replace(/\s+/g, '')
      this.phone = this.phone.substring(0, 11)
      if (this.phone.length > 7) {
        this.UserName =
          this.phone.slice(0, 3) +
          ' ' +
          this.phone.slice(3, 7) +
          ' ' +
          this.phone.slice(7)
      } else if (this.phone.length > 3) {
        this.UserName = this.phone.slice(0, 3) + ' ' + this.phone.slice(3)
      } else {
        this.UserName = this.phone
      }
      // this.UserName = event.detail.value //input输入的内容
      if (data.length > 0) {
        this.showClearIcon = true //小叉叉
      } else {
        this.showClearIcon = false //小叉叉
      }
    },
    //当input框获取焦点的时候，显示小标题，隐藏默认提示文字
    showSmalltitle() {
      this.placeholder = '' //input默认提示字
      this.showtitle = true //小标题的显示隐藏
      this.isFocus = true
    },
    //当input框失去焦点的时候，隐藏小标题，显示默认提示文字
    hideSmalltitle() {
      if (this.UserName === '') {
        this.placeholder = '请输入手机号' //input默认提示字
        this.showtitle = false //小标题的显示隐藏
				 this.isFocus = false
      }

    },
    //勾选免责
    Agree() {
      this.isAgree = !this.isAgree
    },
    //历史号码点击
    selHistory(data) {
      if(data){
        this.UserName = data
        this.phone = data.replace(/\s+/g, '')
        this.placeholder = '' //input默认提示字
        this.showtitle = true //小标题的显示隐藏
        this.isFocus = false
        this.showClearIcon = true //小叉叉
      }
    },
    //获取验证码
    getCode() {
      if (!/^1[3456789]\d{9}$/.test(this.phone)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none',
        })
      } else if (this.btnText === '获取验证码') {
        if (this.isAgree) {
          this.showPopup = true //弹出免责弹框
        } else {
          uni.navigateTo({
            url: '/pages_login/enterCode/enterCode?UserName=' + this.phone + '&isRegister=' + this.isRegister,
          })
        }
      } else {
        this.quickLogin()
      }
    },

    //快捷登录
    async quickLogin() {
      const systemInfo = uni.getSystemInfoSync()
      let plat = ''
      // #ifdef APP-PLUS
      plat = '_APP'
      //  #endif
      // #ifdef H5
      plat = '_H5'
      //  #endif
      // #ifdef MP-WEIXIN
      plat = '_WEIXIN'
      //  #endif
      console.log(systemInfo)
      let platform = systemInfo.platform
      if(systemInfo.brand){
		  platform = platform + '_' + systemInfo.brand
      }
      if(systemInfo.model){
		  platform = platform + '_' + systemInfo.model
      }
      platform = platform + plat
      try {
        const res = await this.$api.user.quickLogin({
          Mobile: this.phone,
          IMEI: this.$store.state.user.imei,
		  login_Platform: platform,
        })
        this.loginSuccess(res.data)
      } catch (err) {
        console.log(er)
      }
    },
    //同意免责
    agreepopup(type) {
      //type 0同意   1不同意

      if (type === 0) {
        this.isAgree = false
        this.showPopup = false //关闭免责弹框
        this.getCode()
      } else {
        this.isAgree = true
        this.showPopup = false //关闭免责弹框
      }
    },
    //密码登录
    passwordLogin() {
      //老用户 跳转密码输入页面
      //新用户 跳转设置密码页面

      if (this.phone === '') {
        uni.showToast({
          title: '请输入手机号',
          duration: 1000,
          icon: 'none',
        })
      } else if (this.phone.length !== 11) {
        uni.showToast({
          title: '请输入正确的手机号',
          duration: 1500,
          icon: 'none',
        })
      } else if (!/^1[3456789]\d{9}$/.test(this.phone)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none',
        })
      } else {
        uni.navigateTo({
          url:
            '/pages_login/passwordLogin/passwordLogin?UserName=' +
            this.UserName + '&isRegister=' + this.isRegister,
        })
      }
    },
    //跳转协议
    gouserAgreementPage(type) {
      uni.navigateTo({
        url: '/pages_login/userAgreement/userAgreement?type=' + type,
      })
    },

    async verifyMobile(data) {
      try {
        const res = await this.$api.user.verifyMobile({
          IMEI: data,
        })
        console.log(res)
        if (res.data.length > 0) {
          this.historyInfo = res.data.map(item => {
            return (
              item.slice(0, 3) + ' ' + item.slice(3, 7) + ' ' + item.slice(7)
            )
          })
          console.log(this.historyInfo)
          if (res.data.length === 1) {
            this.quickUser = res.data[0]
            this.phone = res.data[0]
            this.UserName = this.historyInfo[0]
            this.showtitle = true //显示小标题
            this.showClearIcon = true //显示小叉叉
            this.placeholder = '请输入手机号'
          }
        }
      } catch (e) {}
    },

    //保存登录信息
    loginSuccess(param) {
      this.$store.commit('user/setUserInfo', param)
      this.$store.commit('setUserInfo', param)
      //token存储
			 uni.setStorageSync('token', param.token)
      // uni.setStorage({
      //   key: 'token',
      //   data: param.token,
      // })
      //用户信息存储
			 uni.setStorageSync('Ztc_B_USER_INFO', param)
      // uni.setStorage({
      //   key: 'Ztc_B_USER_INFO',
      //   data: param,
      // })
      this.getUserInfo(() => {
        if (this.$store.state.needPageBack) {
          uni.navigateBack({
            delta: 1,
          })
        } else if (param.infoDegree === 'BothNone') {
          this.getUserCompany()
          uni.showToast({
            title: '您的资料尚未认证完成，请继续认证',
            icon: 'none',
            duration: 3000,
          })
        } else if (param.infoDegree === 'IdentityInfoNone') {
          uni.showToast({
            title: '您的资料尚未认证完成，请继续认证',
            icon: 'none',
            duration: 3000,
          })
          setTimeout(() => {
            uni.navigateTo({
              url: '/pages_login/authenticationPersonal/authenticationPersonal',
            })
          }, 3000)
        } else if (param.infoDegree === 'StoreInfoNone') {
          uni.showToast({
            title: '您的资料尚未认证完成，请继续认证',
            icon: 'none',
            duration: 3000,
          })
          setTimeout(() => {
            uni.navigateTo({
              url: '/pages_login/authenticationCompany/authenticationCompany',
            })
          }, 3000)
        } else if (
          param.infoDegree === 'StoreInfoWait' ||
          param.infoDegree === 'JoinCompanyWait'
        ) {
          uni.navigateTo({
            url: '/pages_login/authenticationState/authenticationState?state=0&phone='+this.UserName, //审核状态
          })
        } else if (
          param.infoDegree === 'StoreInfoDefault' ||
          param.infoDegree === 'JoinCompanyDefault'
        ) {
          uni.navigateTo({
            url: '/pages_login/authenticationState/authenticationState?state=2&phone='+this.UserName, //审核状态
          })
        } else {
          uni.reLaunch({
            url: '/pages/index/index',
          })
        }
      })
      //   uni.reLaunch({
      //   url: '/pages/index/index'
      // })
      // return
    },

    getUserCompany() {
      const _this = this
      this.$api.user.getUserCompany().then(res => {
        if (res.data.name) {
          _this.$store.commit('user/setCompanyInfo', {
            name: res.data.name,
            isJoinCompany: !res.data.isNew,
          })
          uni.navigateTo({
            url:
              '/pages_login/authenticationPersonal/authenticationPersonal?companyName=' +
              res.data.name,
          })
        } else {
          uni.navigateTo({
            url: '/pages_login/register/register',
          })
        }
      })
    },

    //获取用户信息
    async getUserInfo(cb) {
      try {
        const res = await this.$api.user.getUserInfo()
        uni.setStorageSync('userInfoDetail', res.data)
        this.$store.commit('setUserInfoDetail', res.data)
        cb()
      } catch (e) {
        //TODO handle the exception
      }
    },

    //用户是否注册
    checkIsRegister() {
      // uni.showLoading()
      this.$api.user
        .isRegister({
          type: 1,
          mobile: this.phone,
        })
        .then(res => {
          this.isRegister = res.data
          if (res.data) {
            this.isAgree = false
          } else {
            this.isAgree = true
          }
          // uni.hideLoading()
        })
        .catch(err => {
          // uni.hideLoading()
          console.log(err)
        })
    },
  },
}
